<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 公共继承控制器
 * @author www.dingwei.cn
 *
 */
class MY_Controller extends CI_Controller{
	public $isDEBUG = false;
	public $mUser = null; //临时定义一个 待删除
	public $terminal = '';   	//判断访问终端
	public $terminalDir = '';   //终端访问路径
	public $port = '';	 		//访问端口
	public $portDir = '';	 	//端口路径
	public $ruri = '';    		//当前访问的uri (对应的是程序目录)
	public $isAjax = false; 	//判断是否是ajax请求
	public $staticUrl = '';		//静态文件目录
	public $uriDir  = '';   	//使用路由后的目录
    public $adminPermissions = array();	//登录人权限

	/**
	 * 用户信息
	 * @var integer
	 */
	public $userId = 0;			//登录人的id
	public $userName = '';		//用户名
	public $userRank = '';		//用户等级
	public $userMobile  = 0;   	//登录人手机号码
	public $userBalance  = 0;   	//登录人账户余额
    public $hasPasswd = false;
	public $userIntegral= 0;   	//登录人账户积分
	public $userExperienceValue= 0;   	//登录人经验值
	public $userPortrait  = ''; //头像
	public $userJpushCode  = 0; //激光推送
	public $sessionId  = '';   	//登录标识id
	public $userType = 0;  		//后端管理员(1:大后台管理员， 2：区域管理员 3：监督管理员)   前端（1：消费者   2：商户  3：配送员）
	public $userOrderType = array(); //配送员接单类型  

    /**
     * 微信
     */
    public $latitude = 0;
    public $longitude = 0;
    public $address = '';

    /**
     * 商户信息
     */
    public $userCategoryId  = 0;   	//店铺类型

	/**
	 * 平台信息
	 * @var string
	 */
	public $isAdmin = false;	//是否是后台的管理员
	
	/**
	 * 区域管理员
	 * @var string
	 */
	public $isCounty = false;	//是否是区域管理员
	public $userArea = '';//区域名称
	public $countyItem = '';//管理区域
	public $userCountyId = [];//管理id

    /**
     * 监督管理员
     * @var string
     */
    public $isSupervise = false;	//是否是监督管理员

	/**
	 * 假索引
	 * @var CI_DB
	 */
	public $db;
	
	public function __construct(){
        parent::__construct();

        $this->ruri = $this->uri->ruri_string();
        $this->uriDir = $this->uri->segment(1);
		$this->port = $this->_getPort();
		$this->terminal = $this->_getTerminal();
		$this->staticUrl = base_url('static').'/';
		if (isset($_SERVER["HTTP_X_REQUESTED_WITH"])
				&& strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) == "xmlhttprequest"){//ajax提交
			$this->isAjax = true;
		}
		
		if( ! $this->port || ! $this->terminal){
			
			if($this->isAjax){
				$this->ajaxReturn(0, '路径错误');
			}
			
			if( ! $this->port){

				redirect(getUrl('home', 'area', 'pc'));
			}
		}
		$uri = strtolower($this->ruri);
		$sessionId = decode($this->input->post('sessionid'));

		if($this->port == 'admin' || $this->port == 'county'){  //后台管理
			$noLogin = false;
			$noLoginC = getCustomConfig('no_login', $this->port);
			foreach ($noLoginC as $v){
				if(strpos($uri, strtolower($v)) > 0){
					$noLogin = true;
					break;
				}
			}
			if($this->port == 'county'){
				//区域管理员
				$this->loadModel('CtyUserModel', 'mUser', $this->port);
				$this->userType = 2;
				if($this->terminal == 'pc'){
					if($noLogin){
						return '';
					}
					
					//判断是否登录
					if(empty($_COOKIE['county_sessionid'])){
						redirect(getUrl('login', $this->port));
					}
					$sessionid = decode($_COOKIE['county_sessionid']);
					if( ! $sessionid){
						redirect(getUrl('login', $this->port, 'pc'));
					}
					$tA = $this->mUser->getUserInfoBySessionid($sessionid);
					if( ! $tA){
						redirect(getUrl('login', $this->port, 'pc'));
					}
                    $tA = $this->mUser->getUserInfoBySessionid($sessionid);

                    $this->countyItem = $this->mUser->getCountyItem($tA['id'], true);
					$this->isCounty = true;
					$this->userName = $tA['manager'];
					$this->userArea = $tA['section_name'];
                    $this->adminPermissions = isset($tA['permissions']) ? $tA['permissions'] : array();

					return;
				}
			}
			else{
				$this->loadModel('AdmUserModel', 'mUser', $this->port);
				$this->userType = 1;
				
				if($this->terminal == 'pc'){
					if($noLogin){
						return '';
					}
					
					//判断是否登录
					if(empty($_COOKIE['admin_sessionid'])){
						redirect(getUrl('login', $this->port));
					}
					$sessionid = decode($_COOKIE['admin_sessionid']);
					if( ! $sessionid){
						redirect(getUrl('login', $this->port, 'pc'));
					}
					$tA = $this->mUser->getUserInfoBySessionid($sessionid);
					if( ! $tA){
						redirect(getUrl('login', $this->port, 'pc'));
					}
					
					$this->isAdmin = isset($tA['type']) && $tA['type'] == 1 ? true : false;
					$this->userId = $tA['id'];
					$this->userName = $tA['name'];
                    $this->adminPermissions = isset($tA['permissions']) ? json_decode($tA['permissions'], true) : array();

                    $uri = $this->getAdminPermissionsKeyByUri();

                    if( ! $this->adminAuthority($uri[1], $uri[0])){
                        if($this->isAjax){
                            $this->ajaxReturn(0, '无权限操作');
                        }else{
                            show_error('无权限操作');
                        }
                    }
					return;
				}
			}
			
		}elseif($this->port == 'deliveryman'){
		    
		    $this->loadModel('DlnUserModel', 'mUser', $this->port);
		    $fileter = true;
		    if($this->terminal == 'app'){
		        $config = getCustomConfig('no_login', $this->port);
		    }else{
		        $config = getCustomConfig('pc_no_login', $this->port);
		    }
		    
		    foreach ($config as $v){
		        if(strpos($uri, strtolower($this->portDir.'/'.$this->terminalDir.'/'.$v)) === 0){
		            $fileter = false;
		            break;
		        }
		    }
		    
		    $isWap = false;
		    $sessionId = '';
		    if($this->terminal == 'app'){
		        $sessionId = post('sessionid');
		        if( ! $sessionId && $fileter){
		            $this->appReturn(0, '参数sessionid必须', array('error_code' => '00001'));
		        }
		        
		        $sessionId = decode($sessionId);
		        if( ! $sessionId && $fileter){
		            $this->appReturn(0, '参数sessionid错误', array('error_code' => '00001'));
		        }
		    }
		    
		    $userInfo = array();
		    if($sessionId){
		        $userInfo = $this->mUser->getInfoBySessionid($sessionId, 1);
		    }
		    
		    if($this->terminal == 'app' && $fileter){
		        if( ! $userInfo){
		            $this->appReturn(0, '账号已在别处登陆，本地已退出', array('error_code' => '00001'));
		        }
		        
		        if($userInfo['status'] == 4){
		            $this->appReturn(0, '账号已禁用', array('error_code' => '00001'));
		        }
		    }else if($fileter){
		        show_404();
		    }
		    
		    if($userInfo){
		        $this->sessionId = $sessionId;
		        $this->userId = $userInfo['id'];
		        $this->userMobile = $userInfo['mobile'];
		        $this->userName = $userInfo['name'];
		        $this->userStatus = $userInfo['status'];
		        $this->userCountyId = $userInfo['county_id'];
		        $this->userOrderType = $userInfo['order_type'];
		    }
		    return;
		}elseif($this->port){

			if($this->port == 'consumer'){
				$this->loadModel('ConsumerUserModel', 'mUser', $this->port);
				if (FALSE){
					//临时添加索引，并不起任何作用
					$this->mUser = new ConsumerUserModel();
				}
				$this->userType = 1;
			}elseif($this->port == 'merchant'){
				$this->loadModel('MerchantUserModel', 'mUser', $this->port);
                if (FALSE){
                    //临时添加索引，并不起任何作用
                    $this->mUser = new MerchantUserModel();
                }
				$this->userType = 2;
			}elseif($this->port == 'deliveryman'){
                $this->loadModel('DlnUserModel', 'mUser', $this->port);
            }

			$fileter = true;
			if($this->terminal == 'app'){
				$config = getCustomConfig('no_login', $this->port);
			}elseif($this->terminal == 'wx'){
                $config = getCustomConfig('wx_no_login', $this->port);
            }else{
				$config = getCustomConfig('pc_no_login', $this->port);
			}
            $s = false;
			if ($this->terminal == 'wx'){
//                $_COOKIE['wx_sessionid'] = encode('8fda4f5c8a7a90564ff2ba76651120729dd1c4fd');
                $s = $this->getSessionId();

            }

            if ($s == false) {
                foreach ($config as $v) {
                    if (!$sessionId && strpos($uri, strtolower($this->portDir . '/' . $this->terminalDir . '/' . $v)) === 0) {
                        $fileter = false;
                        break;
                    }
                }
            }
			if ($this->terminal == 'wx' && !empty($_COOKIE['coordinate'])){
                $coordinate = decode($_COOKIE['coordinate']);
                $coordinate = json_decode($coordinate);
                $this->latitude = $coordinate[0];
                $this->longitude = $coordinate[1];
                $this->address = $coordinate[2];
            }

			if(($this->terminal == 'app' || $this->terminal == 'wx') && ! $fileter){
				return;		
			}

            if($this->terminal == 'app'){
                $sessionId = post('sessionid');
                if( ! $sessionId){
                    $this->appReturn(0, '参数sessionid必须', array('error_code' => '00001'));
                }

                $sessionId = decode($sessionId);
                if( ! $sessionId){
                    $this->appReturn(0, '参数sessionid错误', array('error_code' => '00001'));
                }
            }else{
//                $sessionId = encode('79f6782c66366e0f5dc034006819a4722e4e984b'); // $_COOKIE['wx_sessionid'];//
                if(!isset($_COOKIE['wx_sessionid']) || !$_COOKIE['wx_sessionid']){
                    if ($this->isAjax) {
                        $this->appReturn(0, '请登录后操作', array('error_code' => '00001'));
                    }else{
                        redirect(getUrl('user/login'));
                    }
                }

                $sessionId = $_COOKIE['wx_sessionid'];
            }

			if($this->terminal == 'wx'){
                if( ! $sessionId){
                    if ($this->isAjax) {
                        $this->appReturn(0, '参数sessionid必须', array('error_code' => '00001'));
                    }else{
                        show_error('参数sessionid必须');
                    }
                }

                $sessionId = decode($sessionId);

                if( ! $sessionId){
                    if ($this->isAjax) {
                        $this->appReturn(0, '参数sessionid错误', array('error_code' => '00001'));
                    }else{
                        show_error('参数sessionid必须');
                    }
                }
            }



			if($this->terminal == 'app'){
                $userInfo = $this->mUser->getInfoBySessionid($sessionId, 1);
				if( ! $userInfo){
                    $this->appReturn(0, '账号已在别处登陆，本地已退出', array('error_code' => '00001'));
				}
				
				if($userInfo['status'] == 1){
                    $this->appReturn(0, '账号已禁用', array('error_code' => '00001'));
				}
			}elseif($this->terminal == 'wx'){
                $userInfo = $this->mUser->getInfoBySessionid($sessionId, 2);
                if( ! $userInfo){
                    if ($this->isAjax){
                        $this->appReturn(0, '账号已在别处登陆，本地已退出', array('error_code' => '00001'));
                    }else{
                        redirect(getUrl('user/login'));
                        //show_error('账号已在别处登陆，本地已退出');
                    }
                }

                if($userInfo['status'] == 1){
                    if ($this->isAjax) {
                        $this->appReturn(0, '账号已禁用', array('error_code' => '00001'));
                    }else{
                        setcookie('wx_sessionid', '', time()+3600*24, '/');
//                        show_error('账号已禁用');
                    }
                }elseif ($userInfo['status'] == -1){
                    setcookie('wx_sessionid', '', time()+3600*24, '/');
//                    show_error('账号已删除');
                }
            }else{
				show_404();
			}

			if($userInfo){
				$this->sessionId = $sessionId;
				$this->userId = $userInfo['id'];
				$this->userMobile = $userInfo['mobile'];
				$this->userBalance = empty($userInfo['balance']) ? '0':$userInfo['balance'];
				$this->hasPasswd = empty($userInfo['pay_passwd'])?false:true;
				$this->userIntegral = empty($userInfo['integral']) ? '0':$userInfo['integral'];
				$this->userExperienceValue = empty($userInfo['experience_value']) ? '0':$userInfo['experience_value'];
				$this->userCategoryId = empty($userInfo['category_id']) ? '0':$userInfo['category_id'];
				$this->userName = isset($userInfo['nickname'])? $userInfo['nickname']:'';
				$this->userRank = isset($userInfo['rank'])? $userInfo['rank']:'';
				$this->userPortrait = $userInfo['portrait'];
				$this->userJpushCode = $userInfo['jpush_code'];
                $this->userStatus = isset($userInfo['status'])?$userInfo['status']:'';
                $this->userCountyId = isset($userInfo['county_id'])?$userInfo['county_id']:'';
                $this->userOrderType = isset($userInfo['order_type'])?$userInfo['order_type']:'';
			}

			return;
		}

		show_404();
	}
	
	/**
	 * 获取后台所有的菜单
	 * @param	array	$menu	//菜单数据
	 * @return	array()
	 */
//	public function getAdminMenu(){
//
//		$menu = array();
//		if($this->port == 'county'){
//			$menu = getCustomConfig('menu', 'county');
//		}else{
//			$menu = getCustomConfig('menu', 'admin');
//		}
//
//		$data = array(
//				'application' => array(),	//应用模块
//				'local' => array()			//本地模块
//		);
//
//		$tUri = str_replace($this->terminalDir.'/', '' ,str_replace($this->portDir.'/', '', $this->ruri));
//		$selected = 1;
//		foreach ($menu as $k => $v){
//            $b = false;
//            foreach ($v['permissions'] as $kkk => $vvv){
//                if($this->adminAuthority($k.'-'.$kkk, $k) && $this->port == 'admin'){
//                    $b = true;
//                    break;
//                }
//            }
//
//			$uri = $v['url'];
//			if(isset($v['sub_menu'])){
//				foreach ($v['sub_menu'] as $vv){
//					$uri = $vv['url'];
//					break;
//				}
//			}
//
//			$menu[$k]['url'] = $uri;
//
//			//选中
//			if(isset($v['sub_menu']) && $selected == 1){
//
//				foreach ($v['sub_menu'] as $kk => $vv){
//					if(strpos($tUri, $vv['url']) === 0){
//						$selected = 2;
//						$menu[$k]['sub_menu'][$kk]['selected'] = true;
//						break;
//					}
//				}
//			}elseif( ! isset($v['sub_menu'])){
//
//				if(strpos($tUri, $v['url']) === 0){
//					$selected = 2;
//					$menu[$k]['selected'] = true;
//					break;
//				}
//			}
//
//			if($selected == 2){
//				$menu[$k]['selected'] = true;
//				$selected = 3;
//			}
//		}
//
//		return $menu;
//	}
    public function getAdminMenu(){
        $menu = getCustomConfig('menu', $this->port);
        $tUri = str_replace($this->terminalDir.'/', '' ,str_replace($this->portDir.'/', '', $this->ruri));
        $selected = 1;
        foreach ($menu as $k => $v){

			if( ! $this->adminAuthority('', $k) && $this->port == 'admin'){
				unset($menu[$k]);
				continue;
			}

            $uri = '';
            if(isset($v['sub_menu'])){
                foreach ($v['sub_menu'] as $kk => $vv){

                    $b = false;
                    foreach ($vv['permissions'] as $kkk => $vvv){

                        if($this->adminAuthority($kk.'-'.$kkk, $k) && $this->port == 'admin'){
                            $b = true;
                            break;
                        }
                    }

                    if( ! $uri){
                        $uri = $vv['url'];
                    }

                    if( ! $b && $this->port == 'admin'){
                        unset($menu[$k]['sub_menu'][$kk]);
                        unset($v['sub_menu'][$kk]);
                    }

//                    break;
                }
            }

            $menu[$k]['url'] = $uri ? $uri : $v['url'];

            //选中
            if(isset($v['sub_menu']) && $selected == 1){

                foreach ($v['sub_menu'] as $kk => $vv){
                    if(strpos($tUri, $vv['url']) === 0){
                        $selected = 2;
                        $menu[$k]['sub_menu'][$kk]['selected'] = true;
                        break;
                    }
                }
            }elseif( ! isset($v['sub_menu'])){

                if(strpos($tUri, $v['url']) === 0){
                    $selected = 2;
                    $menu[$k]['selected'] = true;
                    break;
                }
            }

            if($selected == 2){
                $menu[$k]['selected'] = true;
                $selected = 3;
            }
        }

        return $menu;
    }
	/**
	 * 获取访问的终端
	 * 
	 * @return	string
	 */
	private function _getTerminal(){
		
		$uri = strtolower($this->ruri);			
		$posts = getCustomConfig('terminal');
		foreach ($posts as $k => $v){
			if(strpos($uri, strtolower($v)) !== false){
				$this->terminalDir = $v;
				return $k;	
			}	
		}
		
		return '';
	}
	
	/**
	 * 获取访问端口
	 * 
	 * @return	string
	 */
	private function _getPort(){
		
		$uri = strtolower($this->ruri);
		$terminals = getCustomConfig('port');
		foreach ($terminals as $k => $v){
			if(strpos($uri, strtolower($v)) !== false){
				$this->portDir = $v;
				return $k;
			}
		}
		
		return '';
	}
	
	/**
	 * 加载model对象
	 * @param	string	$model		模型名称
	 * @param	string	$obj		对象名称
	 * @param	string	$port		指定的端口key
	 * @return	void
	 */
	public function loadModel($model, $obj, $port = ''){
		
		$path = $this->portDir;
		if($port){
			$tA = getCustomConfig('port');
			if( ! isset($tA[$port])){
				return;
			}
			$path = $tA[$port];
		}

		$path .= '/'.$model;
		$this->load->model($path, $obj);		
	}
	
	/**
	 * 加载模板
	 * 
	 * @param	 string 	$view		模板路径
	 * @param	 array		$return		向页面传入的数据
	 * @param	 string		$port		传入的端口
	 * @param	 string		$terminal	传入的终端
	 * @param	 boolean 	$return		是否以字符串方式返回模板（true：返回|false:不返回）
	 * @return	 void|string	 
	 */
	public function view($view, $data = array(), $plugins = '', $terminal = '', 
			$port = '', $return = false){
		$path = $this->portDir;
		if($port){
			$tA = getCustomConfig('port');
			if( ! isset($tA[$port])){
				return;
			}
			$path = $tA[$port];
		}
		
		if( ! $data) $data = array();
		
		if($plugins){
			$data['plugins'] = $plugins;
		}
		
		if($terminal){
			$tA = getCustomConfig('terminal');
			if( ! isset($tA[$terminal])){
				return;
			}
			$path .= '/'.$tA[$terminal];
		}else{
			$path .= '/'.$this->terminalDir;
		}
		
		$path .= '/'.$view;
		if($this->port == 'admin' || $this->port == 'county' ){
			$data['menu'] = $this->getAdminMenu();
		}elseif($this->terminal == 'pc'){
// 			$this->loadModel('AdmSettingModel', 'mSett', 'admin');
// 			$tA = $this->mSett->getSetting('copyright,site_name,operation_center');
// 			$data['copyright'] = $tA['copyright'];
// 			$data['site_name'] = $tA['site_name'];
// 			$data['operation_center'] = json_decode($tA['operation_center'], true);
		}

		if($return){
			return $this->load->view( $path, $data, $return);
		}else{
			$this->load->view($path, $data);
		}
	}
	
	/**
	 * 验证表单提交的数据
	 * 
	 * @param	 array			$config			验证规则 
	 * @param	 array			$data			制定要验证的数据
	 * @param	 boolean 		$returnError	是否返回错误信息（true：返回|false:不返回）
	 * @return	 boolean|array	
	 */
	protected function formDataValidation($config, $returnError = false, $data = array()){

        $this->load->library('form_validation');
        	
        if($data){
        	$this->form_validation->set_data($data);
        }
        foreach ($config as $v) {
        	$this->form_validation->set_rules($v[0], $v[1], $v[2], isset($v[3]) ? $v[3] : null);
        }
        
		if ($this->form_validation->run() == FALSE){
        	$error = $this->form_validation->error_array();
        	if($returnError){
        		return $error;
        	}else{
        		if($this->terminal == 'app'){
        			$this->appReturn(0, $error);
        		}else{
        			foreach ($error as $v){
        				if($this->isAjax){
	        				$this->ajaxReturn(0, $v, null);
        				}else{
        					show_error($v);
        				}
        				break;
        			}
        		}
        	}
        }

        return true;
	}
	
	/**
	 * app接口调用返回
	 * @param	integer	$status		状态（1：成功  0:失败）
	 * @param 	fix		$message	消息
	 * @param 	array	$data		返回的数据
	 * @return	void
	 */
	public function appReturn($status, $message = '', $data = null){
	
		if(is_array($message)){
			foreach ($message as $v){
				$message = $v;
				break;
			}
			
			if(empty($message))
			$message = '';
		}
		
		if(empty($data)){
			$data = array();
		}
		
		$data = array('status' => $status, 'message' => $message, 'data' => $data);
		exit(json_encode($data));
	}
	
	/**
	 * ajax返回参数
	 *
	 * @param 	integer		$status		返回状态（0：失败|1：成功）
	 * @param 	array		$data		返回数据
	 * @param 	string		$message	执行的信息描述
	 * @param	array		$formError	表单验证错误信息
	 * @param	string		$url		成功后跳转的url
	 * @return	void
	 */
	public function ajaxReturn($status,  $message = '', $data = array(), $url = ''){
	
		exit(json_encode(array('status' => $status,
				'data' => $data,
				'message' => $message,
				'url' => $url)));
	}
	
	/**
	 * appWap错误提示
	 * @param string $message
	 */
	public function showAppWapError($message){
		
		redirect(getUrl('error/'.$message));
		exit;
	}
	
	/**
	 * 获取wap版的token
	 */
	protected function _getWapToken(){
		return base64_encode(encode($this->sessionId, getCustomConfig('wap_token_key')));
	}
	
	/**
	 * 上传文件
	 */
	public function uploadImge(){

		if( ! isset($_FILES['Filedata'])){
			$this->ajaxReturn(0, '上传失败');
		}
		
		$path = 'uploads/temp';
		$tA = imageUpload($path, 'Filedata', date('ymdhis').rand(1000, 100000),true);
		$img = '';
		if($tA['status']){
			exit(base_url($tA['data']));
		}

		$this->ajaxReturn(0, '上传失败');
	}
    /**
     * 上传文件
     */
    public function uploadImgs(){

        if( ! isset($_FILES['file'])){
            $this->ajaxReturn(0, '上传失败');
        }

        $path = 'uploads/temp';
        $tA = imageUpload($path, 'file', date('ymdhis').rand(1000, 100000),true);
        $img = '';
        if($tA['status']){
            exit(base_url($tA['data']));
        }

        $this->ajaxReturn(0, '上传失败');
    }
	/**
	 * 后台验证权限
	 * @param 	string 	$key
	 * @param 	string 	$module
	 * @return	boolean
	 */
	public function adminAuthority($key, $module = ''){
		if($this->isAdmin || ! $module) return true;

		if( ! isset($this->adminPermissions[$module])) return false;

		if( ! $key && isset($this->adminPermissions[$module])){
			return true;
		}
		
		if(in_array($key, $this->adminPermissions[$module])){
			return true;
		}

		return false;
	}

    /**
     * 获取当前访问的网址的权限key
     *
     * @return	string
     */
    public function getAdminPermissionsKeyByUri(){

        $appPath = getCustomConfig('app_base_path');
        $uri = trim(str_replace($this->terminal, '', str_replace($this->port, '', uri_string())), '/');
        $module = getCustomConfig('menu', 'admin');
        $moduledata = array();
        foreach ($module as $kk => $vv){

            if(isset($vv['sub_menu'])){
                foreach ($vv['sub_menu'] as $kkk => $vvv){

                    $url = $vvv['url'];
                    if($url == $uri){
                        return array($kk, $kkk.'-view');
                    }

                    if(isset($vvv['permissions'])){
                        foreach ($vvv['permissions'] as $kkkk => $vvvv){
                            foreach ($vvvv['uri'] as $vvvvv){

                                $tSuri = trim(strtolower($vvv['url'].'/'.$vvvvv), '/');
                                if($uri == $tSuri || $uri.'/index' == $tSuri){
                                    return array($kk, $kkk.'-'.$kkkk);
                                }
                            }
                        }
                    }
                }
            }else{
                $url = $vv['url'];
                if($url == $uri){
                    return array($kk, 'view');
                }

                if(isset($vv['permissions'])){
                    foreach ($vv['permissions'] as $kkk => $vvv){
                        foreach ($vvv['uri'] as $vvvv){
                            $tSuri = trim(strtolower($url.'/'.$vvvv), '/');
                            if($uri == $tSuri || $uri.'/index' == $tSuri){
                                return array($kk, $kkk);
                            }
                        }
                    }
                }
            }
        }

        return array('', '');
    }

    /**
	 * 获取状态显示样式
	 * @param 	integer $status
	 * @return	string
	 */
	protected function adminStatus($status = null, $show = false){
		
		$config = array(1 => '禁用', 2 => '启用');
		if( ! $status){
			return $config;
		}
		
		if($status && ! isset($config[$status])){
			return '';
		}
		
		if( ! $show){
			return $config[$status];
		}
		
		
		if($status == 1){
			return '<span class="label label-danger">'.$config[$status].'</span>';
		}else if($status == 2){
			return '<span class="label label-success">'.$config[$status].'</span>';
		}
		
		return'';
	}
	
	/**
	 * 编辑器上传图片
	 */
	public function editor(){
		error_reporting(E_ERROR);
		header("Content-Type: text/html; charset=utf-8");
		$CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents(APPPATH.'libraries/ueditor/config.json')), true);
		$action = $_GET['action'];
		$ext = '';
		$path = 'uploads/temp/'.time();
		$CONFIG['imagePathFormat'] = $path;
	
		$result = '';
		switch ($action) {
			case 'config':
				$result =  json_encode($CONFIG);
				break;
	
				/* 上传图片 */
			case 'uploadimage':
				include(APPPATH.'libraries/ueditor/Uploader.class.php');
				$config = array(
						"pathFormat" => $CONFIG['imagePathFormat'],
						"maxSize" => $CONFIG['imageMaxSize'],
						"allowFiles" => $CONFIG['imageAllowFiles']
				);
				$fieldName = $CONFIG['imageFieldName'];
				$up = new Uploader($fieldName, $config, $base64);
				$tA = $up->getFileInfo();
				if( ! empty($tA['url'])){
					$tA['url'] = base_url($tA['url']);
				}
				$result = json_encode($tA);
				break;
			default:
				$result = json_encode(array(
								'state'=> '请求地址出错'
						));
		}
	
		/* 输出结果 */
		if (isset($_GET["callback"])) {
			if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
				echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
			} else {
				echo json_encode(array(
						'state'=> 'callback参数不合法'
				));
			}
		} else {
			echo $result;
		}
	}
	
	/**
	 * 生成二维码图片
	 */
	public function createCode($url = ''){
		$url = $url ? $url : get('param');
		code($url);	
	}


    /**
     * 判断用户是否登录
     */
    function getSessionId(){
        if(!isset($_COOKIE['wx_sessionid']) || !$_COOKIE['wx_sessionid']){
            return false;
        }
        $sessionId = $_COOKIE['wx_sessionid'];
        $userInfo = $this->mUser->getInfoBySessionid(decode($sessionId), 2);
        if( ! $userInfo){
            return false;
        }
        if(!isset($_COOKIE['wx_openid']) || !$_COOKIE['wx_openid']){
            if($userInfo['openid']){
                setcookie('wx_openid', encode($userInfo['openid']), 0, '/');
            }
        }
        return true;
    }
}